import axios from 'axios';
import qs from 'qs';
import {Message, Loading, MessageBox} from 'element-ui';
import {hostUrl, apis} from '../../config/request.config';
import {getCookie} from './utils.js';

export const request = (options) => {
  options = Object.assign({
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformRequest: [function (data, config) {
      if (!config['Content-Type']) return qs.stringify(data, {arrayFormat: 'brackets'});
      switch (config['Content-Type'].toLowerCase()) {
        case 'application/json;charset=utf-8': {
          return JSON.stringify(data);
        }

        case 'multipart/form-data;charset=utf-8': {
          return data;
        }

        default: {
          return qs.stringify(data, {arrayFormat: 'brackets'})
        }
      }
    }],
  }, options);

  let token = getCookie('token_code');
  if (!token && options.url !== 'Login') {
    MessageBox.alert('登录账号过期，请重新登录', '账号过期', {
      confirmButtonText: '确定',
      callback: () => {
        let origin = window.location.origin;
        // console.log(origin);
        window.location.href = origin;
      }
    });
    return;
  } else if (token) {
    axios.defaults.headers.common['token'] = getCookie('token_code');
  }

  let loading;

  if (!options.method) {
    options.method = 'POST'
  }

  if (options.isShowLoading) {
    loading = Loading.service({
      fullscreen: true,
      text: '加载中...请稍后...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  }

  if (options.host) {
    options.url = options.host + options.url;
  } else {
    options.url = hostUrl + apis[options.url]
  }

  // 清除value为空的键值
  if (options.params) {
    for (var key in options.params) {
      if (options.params[key] === '' || options.params[key] == undefined) {
        delete options.params[key];
      }
    }
  }

  return axios(options).then(res => {
    let result = null;

    if (res.data) {
      if (res.data.code == 0) {
        result = res.data;
      } else {
        Message({
          message: res.data.message,
          type: 'error'
        });
      }
    }

    if (options.isShowLoading) {
      loading.close();
    }

    return result;
  }).catch(() => {
    Message({
      message: '服务器错误，请稍后重试~',
      type: 'error'
    })
    loading.close();
    return null
  })
}
